package com.yuma.tingshu.user.login;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuma.tingshu.account.client.UserAccountFeignClient;
import com.yuma.tingshu.common.constant.RedisConstant;
import com.yuma.tingshu.common.execption.YumaException;
import com.yuma.tingshu.common.result.ResultCodeEnum;
import com.yuma.tingshu.model.user.UserInfo;
import com.yuma.tingshu.user.mapper.UserInfoMapper;
import com.yuma.tingshu.vo.user.UserInfoVo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

//@Component 不需要写，因为这个类被LoginBean注解了，LoginBean中有@Component
@LoginBean(value = LoginType.WX_LOGIN)
public class WxLogin implements LoginInterface {

    @Autowired
    private UserInfoMapper userInfoMapper;

    // 微信码服务
    @Autowired
    private WxMaService wxMaService;

    // 远程调用账号，进行账号初始化
    @Autowired
    private UserAccountFeignClient userAccountFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Map<String, Object> login(LoginAccount account) throws WxErrorException {
        // 1.根据code appid和appsecret调用微信接口 获取openId
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(account.getCode());
        String openid = sessionInfo.getOpenid();
        // 如果获取失败，重新回调登录页面
        if (StringUtils.isBlank(openid)) {
            throw new YumaException(ResultCodeEnum.LOGIN_AUTH);
        }
        // 2.查询mysql获取用户信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        if (userInfo == null) {
            // 3.隐式注册
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友" + redisTemplate.opsForValue().increment(RedisConstant.USER_NICKNAME_KEY));
            userInfo.setAvatarUrl("https://b0.bdstatic.com/ac1b7570f5eb5527a99a0997179662a4.jpg@h_1280");
            userInfo.setStatus("1");
            userInfoMapper.insert(userInfo);
            // 账户tingshu_account库的user_account信息要初始化
            userAccountFeignClient.init(userInfo.getId());
        }

        // 4. 生成uuid作为token保存到Redis中
        String token = UUID.randomUUID().toString();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

        // 5.返回token
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return map;
    }
}